﻿using System;
using System.IO;
using System.Text;
using OS.Common.Enums;
using OS.Common.Utils;

namespace OS.Common.Plugs.LogPlug
{
    /// <summary>
    /// 默认日志插件
    /// </summary>
    public class DefaultLogPlug : ILogPlug
    {
        private readonly string _logBaseDirPath;

        private const string LogFormat = "{0:T}    Code:{1}    Key:{2}   Detail:{3}";

        private readonly object _obj = new object();

        /// <summary>
        /// 构造函数
        /// </summary>
        public DefaultLogPlug()
        {
            _logBaseDirPath = Path.Combine(AppContext.BaseDirectory, "log");
            if (!Directory.Exists(_logBaseDirPath))
            {
                Directory.CreateDirectory(_logBaseDirPath);
            }
        }

        private string GetLogFilePath(string module, LogLevelEnum level)
        {
            var text = string.Format("{0}\\{1}\\{2}\\", this._logBaseDirPath, module, level);
            if (!Directory.Exists(text))
            {
                Directory.CreateDirectory(text);
            }
            return text + DateTime.Now.ToString("yyyyMMddHH") + ".txt";
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="info"></param>
        public void WriteLog(LogInfo info)
        {
            lock (_obj)
            {
                using (var streamWriter = new StreamWriter(new FileStream(this.GetLogFilePath(info.ModuleName, info.Level), FileMode.Append, FileAccess.Write), Encoding.UTF8))
                {
                    streamWriter.WriteLine(LogFormat, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), info.LogCode, info.MsgKey, info.Msg);
                }
            }
        }

        /// <inheritdoc />
        /// <summary>
        /// 生成错误编号
        /// </summary>
        /// <returns></returns>
        public void SetLogCode(LogInfo log)
        {
            log.LogCode = NumberUtil.TimeMilliNumber().ToCode();
        }
    }
}